package com.inews.ui;

import com.inews.R;
import com.inews.util.AuthUtil;
import com.inews.util.JavaScriptUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends Activity implements IWeiboActivity{
	
	private WebView webView;
	private ProgressDialog progressDialog;
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == CLOSE_DLG){
				progressDialog.dismiss();
			}
		};
	};
	private static final int CLOSE_DLG = 1;
	private String url;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.webview);
		url = AuthUtil.getAuthorizationURL();
		if(url == null){
			return;
		}
		init();
		load(url, webView);
	}


	@Override
	public void init() {
		//初始化进度条
		if(progressDialog == null){
			progressDialog = new ProgressDialog(this);
		}
		progressDialog.setMessage("正在加载...");
		progressDialog.show();
		
		webView = (WebView) this.findViewById(R.id.wv_oauth);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new JavaScriptUtil(), "methods");
		
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return true;
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				Log.i("onPageFinished", url);
				if(JavaScriptUtil.pinHtmlAddress.equals(url)){
					view.loadUrl("javascript:window.methods.getPin('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); 
					Intent intent = new Intent(WebViewActivity.this, AccessTokenActivity.class);
					startActivity(intent);
				}
				super.onPageFinished(view, url);
			}
			
			
		});
		
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				System.out.println(newProgress);
				if(newProgress == 100){
					handler.sendEmptyMessage(CLOSE_DLG);
				}
				
				super.onProgressChanged(view, newProgress);
			}
		});
		
	}
  

	@Override
	public void refresh(Object... objects) {
		// TODO Auto-generated method stub
		
	}
	
	
	public void load(final String url, final WebView webView){
		if(url == null || "".equals(url)){
			return;
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				webView.loadUrl(url);
			}
		}).start();
	}
	
	
	

}
